package com.rzico.market.plugin.jd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rzico.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 京东服务工具类，根据实际情况调用api工具类
 */
public class JDServiceUtils {

    /**
     * 获取token值
     * @return
     */
    public static String refrash_token(){
        String token = "";
        String rs = JDApiUtils.refresh_token();
        JDReposeInfo tokenRes = JSONArray.parseObject(rs, JDReposeInfo.class);
        Map<String, Object> map = jsonToMap(tokenRes.getResult());
        token = map.get("access_token").toString();
        return token;
    }

    /**
     * 获取京东商品的skuid集合
     * @param token
     * @return
     */
    public static List<String> selectJDProSku(String token){
        Map<String, Object> skuParams = new HashMap<String, Object>();
        List<String> list = new ArrayList<String>();
        // token
        skuParams.put("token", token);
        for (int i = 1; i < 5; i ++) {
            String skuList = null;
            // 商品池编码
            skuParams.put("pageNum", i);
            //页码
//          skuParams.put("pageNo", 5000);
            // 执行请求，获取商品池商品编码
            String ReposeStr = JDApiUtils.getSkuByPage(skuParams);
            JDReposeInfo skuByPageRes = JSONArray.parseObject(ReposeStr, JDReposeInfo.class);
            if (null != skuByPageRes.getResult()) {
                //根据商品的sku列表，逐条获取商品信息，
                Map<String, Object> skuResult = jsonToMap(skuByPageRes.getResult());
                skuList = skuResult.get("skuIds").toString();
                skuList = skuList.substring(1, skuList.length() - 1);
            }
            String[] skuIds = skuList.split(",");
            for (String s : skuIds) {
                list.add(s);
            }
        }
        return list;
    }

    /**
     * 获取京东商品信息-单个查询
     * @param token
     * @param sku
     * @return
     */
    public static JDProductInfo selectJDProductInfo(String token, String sku){
        JDProductInfo productVo = null;
        Map<String, Object> productParams = new HashMap<String, Object>();
        // token
        productParams.put("token", token);
        // 商品编码，单个查询
        productParams.put("sku", sku);
        String queryExts = "";
        queryExts += "shouhou,wxintroduction";
        productParams.put("queryExts", queryExts);
        String productStr = JDApiUtils.getDetail(productParams);
        JDReposeInfo productRes = JSONArray.parseObject(productStr, JDReposeInfo.class);
        if (StringUtils.isNotEmpty(productRes.getResult())) {
            productVo = JSONArray.parseObject(productRes.getResult(), JDProductInfo.class);
        }
        return productVo;
    }

    /**
     * 获取京东商品信息
     * @param token
     * @param list
     * @return
     */
    public static List<JDProductInfo> selectJDProduct(String token, List<String> list){
        List<JDProductInfo> productList = new ArrayList<JDProductInfo>();
        for (String i :list) {
            Map<String, Object> productParams = new HashMap<String, Object>();
            // token
            productParams.put("token", token);
            // 商品编码，单个查询
            productParams.put("sku", i);
            String queryExts = "";
            queryExts += "shouhou,wxintroduction";
            productParams.put("queryExts", queryExts);
            String productStr = JDApiUtils.getDetail(productParams);
            JDReposeInfo productRes = JSONArray.parseObject(productStr, JDReposeInfo.class);
            JDProductInfo productVo = JSONArray.parseObject(productRes.getResult(), JDProductInfo.class);
            productList.add(productVo);
        }
        return productList;
    }

    /**
     * 获取商品图片信息
     * @param token
     * @param sku
     * @return
     */
    public static String selectJDProductImage(String token, String sku){
        String imageInfo = null;
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        // 商品编码，单个查询
        params.put("sku", sku);
        String reposeStr = JDApiUtils.skuImage(params);
        JDReposeInfo reponseInfo = JSONArray.parseObject(reposeStr, JDReposeInfo.class);
        if (StringUtils.isNotEmpty(reponseInfo.getResult())) {
            Map<String, Object> map = jsonToMap(reponseInfo.getResult());
            imageInfo = map.get(sku).toString();
        }

        return imageInfo;
    }

    /**
     * 获取京东商品上下架状态
     * @param token
     * @param sku
     * @return
     */
    public static JDProductInfo selectJDProductState(String token, String sku){
        JDProductInfo info = null;
        Map<String, Object> productParams = new HashMap<String, Object>();
        // token
        productParams.put("token", token);
        // 商品编码，单个查询
        productParams.put("sku", sku);
        String priceStr = JDApiUtils.skuState(productParams);
        JDReposeInfo productRes = JSONArray.parseObject(priceStr, JDReposeInfo.class);
        if (null != productRes.getResult() && !"".equals(productRes.getResult())) {
            String str = productRes.getResult().substring(1, productRes.getResult().length() - 1);
            info = JSONArray.parseObject(str, JDProductInfo.class);
        }
        return info;
    }

    //判断京东商品可售性
    public static JDProductInfo selectJDProductSaleState(String token, String sku){
        JDProductInfo info = null;
        Map<String, Object> productParams = new HashMap<String, Object>();
        // token
        productParams.put("token", token);
        // 商品编码，单个查询
        productParams.put("skuIds", sku);
        String queryExts = "";
        queryExts += "noReasonToReturn";
        productParams.put("queryExts", queryExts);
        String priceStr = JDApiUtils.check(productParams);
        JDReposeInfo productRes = JSONArray.parseObject(priceStr, JDReposeInfo.class);
        if (null != productRes.getResult() && !"".equals(productRes.getResult())) {
            String str = productRes.getResult().substring(1, productRes.getResult().length() - 1);
            info = JSONArray.parseObject(str, JDProductInfo.class);
        }
        return info;
    }

    /**
     * 获取京东商品价格
     * @param token
     * @param sku
     * @return
     */
    public static JDProductInfo selectJDProductPrice(String token, String sku){
        JDProductInfo priceVo = null;
        Map<String, Object> productParams = new HashMap<String, Object>();
        // token
        productParams.put("token", token);
        // 商品编码，单个查询
        productParams.put("sku", sku);
        String queryExts = "";
        queryExts += "containsTax";
        productParams.put("queryExts", queryExts);
        String priceStr = JDApiUtils.getSellPrice(productParams);
        JDReposeInfo productRes = JSONArray.parseObject(priceStr, JDReposeInfo.class);
        if (null != productRes.getResult() && !"".equals(productRes.getResult())) {
            String str = productRes.getResult().substring(1, productRes.getResult().length() - 1);
            priceVo = JSONArray.parseObject(str, JDProductInfo.class);
        }
        return priceVo;
    }

    //判断商品的库存
    public static JDStockInfo getStock(String token, String skuNums, String area){
        JDStockInfo jdStockInfo = null;
        Map<String, Object> productParams = new HashMap<String, Object>();
        // token
        productParams.put("token", token);
        productParams.put("skuNums", skuNums);
        productParams.put("area", area);
        String priceStr = JDApiUtils.getNewStockById(productParams);
        JDReposeInfo productRes = JSONArray.parseObject(priceStr, JDReposeInfo.class);
        if (null != productRes.getResult() && !"".equals(productRes.getResult())) {
            String str = productRes.getResult().substring(1, productRes.getResult().length() - 1);
            jdStockInfo = JSONArray.parseObject(str, JDStockInfo.class);
        }
        return jdStockInfo;
    }

    //判断商品区域配送限制
    public static Map<String, Object> checkAreaLimit(String token, String skuIds, String province, String city, String county, String town){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("skuIds", skuIds);
        params.put("province", province);
        params.put("city", city);
        params.put("county", county);
        if (StringUtils.isNotEmpty(town)) {
            params.put("town", town);
        }
        String result = JDApiUtils.checkAreaLimit(params);
        JDReposeInfo productRes = JSONArray.parseObject(result, JDReposeInfo.class);
        if (null != productRes.getResult() && !"".equals(productRes.getResult())) {
            String str = productRes.getResult().substring(1, productRes.getResult().length() - 1);
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 根据地址详情转换为京东地址编码
     * @param token
     * @param address
     * @return
     */
    public static Map<String, Object>  getJDAddressFromAddress(String token, String address){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        // 查询地址
        params.put("address", address);
        String resultStr = JDApiUtils.getJDAddressFromAddress(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 提交订单
     * @param token
     * @param map
     * @return
     */
    public static Map<String, Object> submitOrder(String token, Map<String, Object> map){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("thirdOrder", map.get("thirdOrder"));//第三方的订单单号
        params.put("sku", map.get("sku"));//sku参数
        params.put("name", map.get("name"));//收获人姓名
        params.put("province", map.get("province"));//京东一级地址id
        params.put("city", map.get("city"));//京东二级地址id
        params.put("county", map.get("county"));//京东三级地址id
        params.put("town", map.get("town"));//京东四级地址id
        params.put("address", map.get("address"));//收货人地址
        params.put("mobile", map.get("mobile"));//收获人联系电话
        params.put("email", map.get("email"));//公司邮箱
        params.put("invoiceState", 2);//开票方式
        params.put("invoiceType", 2);//发票类型-增值税专用发票
        params.put("selectedInvoiceTitle", 5);//发票类型-单位
        params.put("companyName", map.get("companyName"));//发票抬头
        params.put("invoiceContent", 1);//增值税专用发票-1.明细
        params.put("doOrderPriceMode", 1);//价格检验
        params.put("orderPriceSnap", map.get("orderPriceSnap"));//商品价格信息
        params.put("paymentType", 4);//支付方式-4.账号余额
        params.put("isUseBalance", 1);//支付方式为4时，此值固定为1
        params.put("submitState", 1);//不预占库存--公司合同仅支持不预占库存方式
        params.put("invoiceName", map.get("invoiceName"));//增专票收票人姓名
        params.put("invoicePhone", map.get("invoicePhone"));//收票人电话
        params.put("invoiceProvice", map.get("invoiceProvice"));//增专票收票人所在省--公司地址-省
        params.put("invoiceCity", map.get("invoiceCity"));//增专票收票人所在市--公司地址-市
        params.put("invoiceCounty", map.get("invoiceCounty"));//增专票收票人所在区/县--公司地址-区
        params.put("invoiceAddress", map.get("invoiceAddress"));//增专票收票人所在地址--公司地址
        params.put("regCompanyName", "一般纳税人");//专票资质公司名称
        params.put("regCode", map.get("regCode"));//专票资质纳税人识别号
        String resultStr = JDApiUtils.submitOrder(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        resultMap.put("resultCode", reposeInfo.getResultCode());
        return resultMap;
    }

    /**
     * 查询京东配送信息,获取该订单的运单号
     * @param token
     * @param jdOrderId 京东订单号
     * @return
     */
    public static Map<String, Object> JDOrderTrack(String token, String jdOrderId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("jdOrderId", jdOrderId);
        params.put("waybillCode", "1");
        String resultStr = JDApiUtils.orderTrack(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            Map<String, Object> result  = jsonToMap(str);
            String waybillCode = String.valueOf(result.get("waybillCode"));
            resultMap = jsonToMap(waybillCode.substring(1, waybillCode.length() - 1));
        }
        return resultMap;
    }

    /**
     * 按类型查询京东订单列表
     * @param token
     * @param type 1.新建订单;2.妥投订单（已确认订单）;3.拒收订单
     * @param startDate yyyy-MM-dd（不包含当天）
     * @param endDate
     * @param pageNo
     * @param pageSize
     * @param jdOrderIdIndex
     * @return
     */
    public static Map<String, Object> getOrderList(String token, String type, String startDate, String endDate, Integer pageNo, Integer pageSize, String jdOrderIdIndex){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        if (StringUtils.isNotEmpty(startDate)) {
            params.put("date", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            params.put("endDate", endDate);
        }
        if (StringUtils.isNotEmpty(jdOrderIdIndex)) {
            params.put("jdOrderIdIndex", Long.valueOf(jdOrderIdIndex));
        }
        String resultStr = "";
        if ("1".equals(type)) {
            resultStr = JDApiUtils.checkNewOrder(params);
        } else if ("2".equals(type)) {
            resultStr = JDApiUtils.checkDlokOrder(params);
        } else if ("3".equals(type)) {
            resultStr = JDApiUtils.checkRefuseOrder(params);
        }
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 查询订单详情
     * @param token
     * @param orderId
     * @return
     */
    public static Map<String, Object> getOrderDetail(String token, String orderId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("token", token);
        params.put("jdOrderId", orderId);
        String queryExts = "";
        queryExts += "finishTime,createOrderTime";
        params.put("queryExts", queryExts);
        String resultStr = JDApiUtils.selectJdOrder(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 查询预存款余额的余额(公司账号余额)
     * @param token
     * @param pin
     * @param type
     * @return
     */
    public static Map<String, Object> getBalance(String token, String pin, String type){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> balanceMap = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("pin", pin);
        params.put("type", type);
        String resultStr = JDApiUtils.getUnionBalance(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
            balanceMap = jsonToMap(resultMap.get("balance").toString());
        }
        return balanceMap;
    }

    /**
     * 预存款余额明细查询
     * @param token
     * @param pageNum
     * @param pageSize
     * @param orderId
     * @param startDate yyyyMMdd
     * @param endDate yyyyMMdd
     * @return
     */
    public static Map<String, Object> getBalanceDetail(String token, Integer pageNum, Integer pageSize, String orderId, String startDate, String endDate){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        if (StringUtils.isNotEmpty(orderId)) {
            params.put("orderId", orderId);
        }
        if (StringUtils.isNotEmpty(startDate)) {
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            params.put("endDate", endDate);
        }
        String resultStr = JDApiUtils.getBalanceDetail(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 查询商品售后信息
     * @param token
     * @param orderId
     * @param skuId
     * @param type 1.校验某订单中某商品是否可以提交售后服务;2.根据订单号、商品编号查询支持的服务类型;3.根据订单号、商品编号查询支持的商品返回京东方式
     * @return 1.success-true可申请 false不可申请，result-可申请时返回可申请数量;2.code-退货(10)、换货(20)、维修(30);
     *          3.code-上门取件(4)、客户发货(40)、客户送货(7)
     */
    public static Map<String, Object> getAfterSaleInfo(String token, String orderId, String skuId, String type){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> skuOrderMap = new HashMap<String, Object>();
        skuOrderMap.put("jdOrderId", orderId);
        skuOrderMap.put("skuId", skuId);
        String param = JSON.toJSONString(skuOrderMap);
        params.put("param", param);
        String resultStr = "";
        if ("1".equals(type)) {
            resultStr = JDApiUtils.getAvailableNumberComp(params);
        } else if ("2".equals(type)) {
            resultStr = JDApiUtils.getCustomerExpectComp(params);
        } else if ("3".equals(type)) {
            resultStr = JDApiUtils.getWareReturnJdComp(params);
        }
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if ("1".equals(type)) {
            resultMap.put("success", reposeInfo.getSuccess());
            resultMap.put("result", reposeInfo.getResult());
        } else if ("2".equals(type) || "3".equals(type)) {
            if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
                String str = reposeInfo.getResult();
                List<Map> list = JSONArray.parseArray(str, Map.class);
                resultMap.put("ComponentExport", list);
            }
        }
        return resultMap;
    }

    /**
     * 申请售后
     * @param token
     * @param jdOrDerId
     * @param customerExpect 10.退货；20.换货
     * @param questionDesc 问题描述
     * @param isHasPackage 是否有包装
     * @param packageDesc 包装描述0 无包装 10 包装完整 20 包装破损
     * @param questionPic 问题图片
     * @param name
     * @param mobile
     * @param email 邮箱
     * @param postCode 邮编
     * @param pickwareType 取件方式，4.上门取货；40.客户发货
     * @param pickwareProvince 取件省
     * @param pickwareCity 取件市
     * @param pickwareCounty 取件县
     * @param pickwareVillage 取件乡镇
     * @param pickwareAddress 取件街道地址
     * @param returnwareType 返件方式：自营配送(10),第三方配送(20);
     * @param returnwareProvince 返件省份编码
     * @param returnwareCity 返件市编码
     * @param returnwareCounty 返件区县编码
     * @param returnwareVillage 返件乡镇编码
     * @param address 返件地址
     * @param skuId 商品sku
     * @param skuNum 商品数量
     * @return
     */
    public static Map<String, Object> createAfsApply(String token, String jdOrDerId, Integer customerExpect, String questionDesc, String questionPic,
                                                     Boolean isHasPackage,Integer packageDesc, String name, String mobile, String email, String postCode,
                                                     Integer pickwareType, String pickwareProvince, String pickwareCity, String pickwareCounty,
                                                     String pickwareVillage, String pickwareAddress, Integer returnwareType, Integer returnwareProvince,
                                                     String returnwareCity, String returnwareCounty, String returnwareVillage, String address,
                                                     String skuId, Integer skuNum){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> paramMap = new HashMap<String, Object>();//售后对象
        paramMap.put("jdOrderId", Long.valueOf(jdOrDerId));//京东订单号
        paramMap.put("customerExpect", customerExpect);//10.退货；20.换货
        paramMap.put("questionDesc", questionDesc);//问题描述
        paramMap.put("isNeedDetectionReport", false);//是否需要检测报告
        if (StringUtils.isNotEmpty(questionPic)) {
            paramMap.put("questionPic", questionPic);//问题图片
        }
        paramMap.put("isHasPackage", isHasPackage);//是否有包装
        paramMap.put("packageDesc", packageDesc);//包装描述0 无包装 10 包装完整 20 包装破损
        //设置参数param的客户信息实体，取件信息实体，返件信息实体及申请单明细
        Map<String, Object> customerMap = new HashMap<String, Object>();//客户信息map
        customerMap.put("customerContactName", name);
        customerMap.put("customerTel", mobile);
        customerMap.put("customerMobilePhone", mobile);
        if (StringUtils.isNotEmpty(email)) {
            customerMap.put("customerEmail", email);//客户邮箱
        }
        if (StringUtils.isNotEmpty(postCode)) {
            customerMap.put("customerPostcode", postCode);//客户邮编
        }
        Object asCustomerDto = JSON.toJSON(customerMap);//客户信息实体
        paramMap.put("asCustomerDto", asCustomerDto);//客户信息实体
        Map<String, Object> asPickwareDtoMap = new HashMap<String, Object>();//取件信息实体map
        asPickwareDtoMap.put("pickwareType", pickwareType);//取件类型，4.上门取货；40.客户发货
        if (StringUtils.isNotEmpty(pickwareProvince)) {
            asPickwareDtoMap.put("pickwareProvince", Integer.valueOf(pickwareProvince));//取件省编码
        }
        if (StringUtils.isNotEmpty(pickwareCity)) {
            asPickwareDtoMap.put("pickwareCity", Integer.valueOf(pickwareCity));//取件市编码
        }
        if (StringUtils.isNotEmpty(pickwareCounty)) {
            asPickwareDtoMap.put("pickwareCounty", Integer.valueOf(pickwareCounty));//取件区/县编码
        }
        if (StringUtils.isNotEmpty(pickwareVillage)) {
            asPickwareDtoMap.put("pickwareVillage", Integer.valueOf(pickwareVillage));//取件乡镇编码
        }
        if (StringUtils.isNotEmpty(pickwareAddress)) {
            asPickwareDtoMap.put("pickwareAddress", pickwareAddress);//取件地址
        }
        Object asPickwareDto = JSON.toJSON(asPickwareDtoMap);
        paramMap.put("asPickwareDto", asPickwareDto);//客户信息实体
        Map<String, Object> asReturnwareDtoMap = new HashMap<String, Object>();//返件信息实体map
        asReturnwareDtoMap.put("returnwareType", returnwareType);//返件方式：自营配送(10),第三方配送(20);
        asReturnwareDtoMap.put("returnwareProvince", returnwareProvince);//返件省份编码
        if (StringUtils.isNotEmpty(returnwareCity)) {
            asReturnwareDtoMap.put("returnwareCity", Integer.valueOf(returnwareCity));//返件市编码
        }
        if (StringUtils.isNotEmpty(returnwareCounty)) {
            asReturnwareDtoMap.put("returnwareCounty", Integer.valueOf(returnwareCounty));//返件区/县编码
        }
        if (StringUtils.isNotEmpty(returnwareVillage)) {
            asReturnwareDtoMap.put("returnwareVillage", Integer.valueOf(returnwareVillage));//返件乡镇编码
        }
        asReturnwareDtoMap.put("returnwareAddress", address);//返件地址
        Object asReturnwareDto = JSON.toJSON(asReturnwareDtoMap);
        paramMap.put("asReturnwareDto", asReturnwareDto);//返件信息实体
        Map<String, Object> asDetailDtoMap = new HashMap<String, Object>();//申请单明细map
        asDetailDtoMap.put("skuId", Long.valueOf(skuId));//商品sku
        asDetailDtoMap.put("skuNum", skuNum);//商品数量
        Object asDetailDto = JSON.toJSON(asDetailDtoMap);
        paramMap.put("asDetailDto", asDetailDto);//申请单明细
        String param = JSON.toJSONString(paramMap);
        params.put("param", param);
        String resultStr = JDApiUtils.createAfsApply(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("resultCode", reposeInfo.getResultCode());
        return resultMap;
    }

    /**
     * 填写发运信息
     * @param token
     * @param afsServiceId 服务单号
     * @param freightMoney 运费
     * @param expressCompany 发运公司
     * @param deliverDate 发货日期，格式为yyyy-MM-dd HH:mm:ss
     * @param expressCode 货运单号，最大50字符
     * @return
     */
    public static Map<String, Object> updateSendSku(String token, String afsServiceId, String freightMoney, String expressCompany, String deliverDate, String expressCode){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> sendSkuMap = new HashMap<String, Object>();
        sendSkuMap.put("afsServiceId", Long.valueOf(afsServiceId));
        sendSkuMap.put("freightMoney", new BigDecimal(freightMoney));
        sendSkuMap.put("expressCompany", expressCompany);
        sendSkuMap.put("deliverDate", deliverDate);
        sendSkuMap.put("expressCode", expressCode);
        String param = JSON.toJSONString(sendSkuMap);
        params.put("param", param);
        String resultStr = JDApiUtils.updateSendSku(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("resultCode", reposeInfo.getResultCode());
        return resultMap;
    }

    /**
     * 查询订单下服务单汇总信息
     * @param token
     * @param orderId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public static Map<String, Object> getServiceListPage(String token, String orderId, Integer pageIndex, Integer pageSize){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> serviceMap = new HashMap<String, Object>();
        serviceMap.put("jdOrderId", orderId);
        serviceMap.put("pageIndex", pageIndex);
        serviceMap.put("pageSize", pageSize);
        String param = JSON.toJSONString(serviceMap);
        params.put("param", param);
        String resultStr = JDApiUtils.getServiceListPage(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 查询服务单明细信息
     * @param token
     * @param afsServiceId
     * @param appendInfoSteps
     * @return
     */
    public static Map<String, Object> getServiceDetailInfo(String token, String afsServiceId, List<Integer> appendInfoSteps){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> serviceDetailMap = new HashMap<String, Object>();
        serviceDetailMap.put("afsServiceId", afsServiceId);
        if (0 < appendInfoSteps.size()) {
            serviceDetailMap.put("appendInfoSteps", appendInfoSteps);
        }
        String param = JSON.toJSONString(serviceDetailMap);
        params.put("param", param);
        String resultStr = JDApiUtils.getServiceDetailInfo(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 取消已经生成的服务单
     * @param token
     * @param serviceIdList
     * @param approveNotes
     * @return
     */
    public static Map<String, Object> auditCancel(String token, List<Integer> serviceIdList, String approveNotes){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> cancelMap = new HashMap<String, Object>();
        cancelMap.put("serviceIdList", serviceIdList);
        cancelMap.put("approveNotes", approveNotes);
        String param = JSON.toJSONString(cancelMap);
        params.put("param", param);
        String resultStr = JDApiUtils.auditCancel(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("result", reposeInfo.getResult());
        return resultMap;
    }

    /**
     * 查询退款信息
     * @param token
     * @param orderId 订单号
     * @param refId 服务单号 -非必填
     * @return
     */
    public static Map<String, Object> getOrderPayByOrderId(String token, String orderId, String refId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("orderId", orderId);
        if (StringUtils.isNotEmpty(refId)) {
            params.put("refId", refId);
        }
        String resultStr = JDApiUtils.getOrderPayByOrderId(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult()) && !"[]".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str.substring(1, str.length() - 1));
        }
        return resultMap;
    }

    /**
     * 确认服务单
     * @param token
     * @param customerName 用户姓名
     * @param username 服务单对应的用户username
     * @param afsServiceId 服务单号
     * @return
     */
    public static Map<String, Object> confirmAfsOrder(String token, String customerName, String username, String afsServiceId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("customerName", customerName);
        params.put("username", username);
        params.put("afsServiceId", afsServiceId);
        String resultStr = JDApiUtils.confirmAfsOrder(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("resultCode", reposeInfo.getResultCode());
        resultMap.put("resultMessage", reposeInfo.getResultMessage());
        return resultMap;
    }

    /**
     * 查询订单下服务单汇总列表信息
     * @param token
     * @param username -非必填
     * @param pageIndex
     * @param pageSize
     * @param startDate -yyyy-MM-dd HH:mm:ss
     * @param endDate -yyyy-MM-dd HH:mm:ss
     * @param jdOrderId -非必填
     * @param sku -非必填
     * @return
     */
    public static Map<String, Object> getAfsServiceListPag(String token, String username, Integer pageIndex, Integer pageSize,
                                                           String startDate, String endDate, String jdOrderId, String sku){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        Map<String, Object> afsServiceMap = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(username)) {
            afsServiceMap.put("username", username);
        }
        afsServiceMap.put("pageIndex", pageIndex);
        afsServiceMap.put("pageSize", pageSize);
        afsServiceMap.put("startDate", startDate);
        afsServiceMap.put("endDate", endDate);
        if (StringUtils.isNotEmpty(jdOrderId)) {
            afsServiceMap.put("jdOrderId", jdOrderId);
        }
        if (StringUtils.isNotEmpty(sku)) {
            afsServiceMap.put("sku", sku);
        }
        String param = JSON.toJSONString(afsServiceMap);
        params.put("param", param);
        String resultStr = JDApiUtils.getAfsServiceListPag(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 申请开票接口
     * @param token
     * @return
     */
    public static Map<String, Object> submitInvoice(String token, Map<String, Object> map){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("supplierOrder", map.get("supplierOrder"));//子订单号，批量以英文逗号分割
        params.put("markId", map.get("markId"));//第三方申请单号：申请发票的唯一id标识 (该标记下可以对应多张发票信息)
        params.put("settlementId", map.get("settlementId"));//结算单号（一个结算单号可对对应多个第三方申请单号）
        params.put("invoiceType", map.get("invoiceType"));//发票类型: 2：增值税专用发票 3：电子发票
        params.put("invoiceOrg", map.get("invoiceOrg"));//开票机构ID
        params.put("bizInvoiceContent", map.get("bizInvoiceContent"));//开票内容：1, "明细";100, "大类"
        params.put("invoiceDate", map.get("invoiceDate"));//期望开票时间，格式：2013-11-8
        params.put("title", map.get("title"));//发票抬头
        params.put("enterpriseTaxpayer", map.get("enterpriseTaxpayer"));//纳税人识别号
        params.put("billToParty", map.get("billToParty"));//收票单位 
        params.put("billToer", map.get("billToer"));//收票人
        params.put("billToContact", map.get("billToContact"));//收票人联系电话
        params.put("billToProvince", map.get("billToProvince"));//收票人地址（省）
        params.put("billToCity", map.get("billToCity"));//收票人地址（市）
        params.put("billToCounty", map.get("billToCounty"));//收票人地址（区）
        params.put("billToTown", map.get("billToTown"));//收票人地址（街道）（专票有四级地址则必传，否则传0）
        params.put("billToAddress", map.get("billToAddress"));//收票人地址（详细地址）（
        params.put("invoiceNum", map.get("invoiceNum"));//当前批次子订单总数
        params.put("invoicePrice", map.get("invoicePrice"));//当前批次含税总金额
        params.put("currentBatch", map.get("currentBatch"));//当前批次号
        params.put("totalBatch", map.get("totalBatch"));//总批次数
        params.put("totalBatchInvoiceAmount", map.get("totalBatchInvoiceAmount"));//总批次开发票价税合计
        params.put("billingType", map.get("billingType"));//1-集中开票，2-分别开票（不传默认为集中开票）
        params.put("isMerge", map.get("isMerge"));//合并开票，（不传默认为合并开票）1-合并SKU，空和其他-分别开票
        String resultStr = JDApiUtils.submitInvoice(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("resultCode", reposeInfo.getResultCode());
        resultMap.put("resultMessage", reposeInfo.getResultMessage());
        resultMap.put("result", reposeInfo.getResult());
        return resultMap;
    }

    /**
     * 通过订单号查询对应的第三方申请单号
     * @param token
     * @param jdOrderId 京东订单号
     * @return
     */
    public static Map<String, Object> queryThrApplyNo(String token, String jdOrderId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("jdOrderId", jdOrderId);
        String resultStr = JDApiUtils.queryThrApplyNo(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("resultCode", reposeInfo.getResultCode());
        resultMap.put("resultMessage", reposeInfo.getResultMessage());
        resultMap.put("result", reposeInfo.getResult());
        return resultMap;
    }

    /**
     * 查询第三方申请单号下的发票概要信息
     * @param token
     * @param markId 第三方申请单号
     * @return
     */
    public static Map<String, Object> selectInvoice(String token, String markId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("markId", markId);
        String resultStr = JDApiUtils.selectInvoice(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult()) && !"[]".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 查询发票明细信息
     * @param token
     * @param invoiceId 发票号
     * @param invoiceCode 发票代码
     * @param prefixZero 发票号补0补齐8位
     * @return
     */
    public static Map<String, Object> queryInvoiceItem(String token, String invoiceId, String invoiceCode, String prefixZero) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("invoiceId", invoiceId);
        params.put("invoiceCode", invoiceCode);
        if (StringUtils.isNotEmpty(prefixZero)) {
            params.put("prefixZero", prefixZero);
        }
        String resultStr = JDApiUtils.queryInvoiceItem(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult()) && !"[]".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 纸质发票如果需要邮寄，使用此接口查询配送单号。
     * @param token
     * @param markId 第三方申请单号
     * @return
     */
    public static Map<String, Object> invoiceWaybill(String token, String markId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("markId", markId);
        String resultStr = JDApiUtils.invoiceWaybill(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult()) && !"[]".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str.substring(1, str.length() - 1));
        }
        return resultMap;
    }

    /**
     * 查询发票物流消息信息
     * @param token
     * @param jdOrderId 京东订单号
     * @return
     */
    public static Map<String, Object> queryInvoiceDeliveryNo(String token, String jdOrderId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("jdOrderId", jdOrderId);
        String resultStr = JDApiUtils.queryInvoiceDeliveryNo(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult()) && !"[]".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            List<Map> list = JSONArray.parseArray(str, Map.class);
            resultMap.put("invoiceTrace", list);
        }
        return resultMap;
    }

    /**
     * 取消发票申请
     * @param token
     * @param markId 第三方申请单号
     * @return
     */
    public static Map<String, Object> invoiceCancel(String token, String markId){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("markId", markId);
        String resultStr = JDApiUtils.invoiceCancel(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        resultMap.put("success", reposeInfo.getSuccess());
        resultMap.put("resultCode", reposeInfo.getResultCode());
        resultMap.put("resultMessage", reposeInfo.getResultMessage());
        resultMap.put("result", reposeInfo.getResult());
        return resultMap;
    }

    /**
     * 按发票号查询发票物流信息
     * @param token
     * @param invoiceNumber 发票号码
     * @param invoiceCode 发票代码
     * @return
     */
    public static Map<String, Object> queryLogisticsByInvoiceNumber(String token, String invoiceNumber, String invoiceCode){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("invoiceNumber", invoiceNumber);
        params.put("invoiceCode", invoiceCode);
        String resultStr = JDApiUtils.queryLogisticsByInvoiceNumber(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult()) && !"[]".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 查询推送信息接口
     * @param token
     * @param type
     * @param queryExt
     * @return
     */
    public static Map<String, Object> getMessage(String token, String type, String queryExt){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        // token
        params.put("token", token);
        params.put("type", type);
        if (StringUtils.isNotEmpty(queryExt)) {
            params.put("queryExt", queryExt);
        }
        String resultStr = JDApiUtils.getMessage(params);
        JDReposeInfo reposeInfo = JSONArray.parseObject(resultStr, JDReposeInfo.class);
        if (null != reposeInfo.getResult() && !"".equals(reposeInfo.getResult())) {
            String str = reposeInfo.getResult();
            resultMap = jsonToMap(str);
        }
        return resultMap;
    }

    /**
     * 将json字符串转换为map对象
     * @param str
     * @return
     */
    public static Map<String, Object> jsonToMap(String str) {
        Map<String, Object> params = new HashMap<String, Object>();
        Map mapType = JSON.parseObject(str, Map.class);
        for (Object obj : mapType.keySet()) {
            params.put(obj.toString(), mapType.get(obj));
        }
        return params;
    }

    /**
     * 获取不同值得Integer集合
     * @param dbSkuList
     * @param skuList
     * @return
     */
    public static List<String> compareSku(List<String> dbSkuList, List<String> skuList){
        List<String> resultList = new ArrayList<String>();
        for (String i : skuList) {
            String sku = "jd-" + i;
            if (!dbSkuList.contains(sku)) {
                resultList.add(i);
            }
        }

        return resultList;
    }

    /**
     * 获取商品轮播图信息
     * @param str
     * @param path
     * @return
     */
    public static String getImageMeta(String str, String path){
        String result = "";
        List<JDProductImageInfo> list = new ArrayList<JDProductImageInfo>();
        list = JSONArray.parseArray(str, JDProductImageInfo.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("video", "");
        List<String> imageList = new ArrayList<String>();
        if (5 > list.size()) {
            for (JDProductImageInfo jdp : list) {
                imageList.add(path + jdp.getPath());
            }
        } else {
            for (int i = 0; i < 5; i ++) {
                imageList.add(path + list.get(i).getPath());
            }
        }
        map.put("images", imageList);
        result = JSON.toJSONString(map);
        return result;
    }

    /**
     * 根据字符串信息获取商品详情图片信息
     * @param str
     * @return
     */
    public static String getImageContent(String str){
        String content = "<p>";
        List<String> stringList = getDetailImagePath(str);
        for (String s : stringList) {
            content += "<img class=\"wscnph\" src=\"https://" + s + "\" width=\"100%\" />";
        }
        content += "</p>";
        return content;
    }

    /**
     * 将商品字符串信息根据规则截取获取详情图片路径集合
     * @param s
     * @return
     */
    public static List<String> getDetailImagePath(String s){
        List<String> list = new ArrayList<String>();
        if ("[]".equals(s)) {

        } else {
            //按",分割每张图片的信息段
            String[] str = s.split("\",");
            for (int i = 0; i < str.length; i ++) {
                String path = "";
                String info = "";
                //先判断是否“src”字符串，再判断是否包含“html”字符串，若有则按该字符串分割并取后一段
                if (str[i].contains("src")) {
                    String[] ss = str[i].split("src");
                    info = ss[1];
                } else if (str[i].contains("html")) {
                    String[] ss = str[i].split("html");
                    info = ss[1];
                }  else {
                    info = str[i];
                }
                String prefix = "";
                String suffix = "";
                //获取图片路径前缀
                if (info.contains("http")) {
                    prefix = "http";
                } else {
                    if (info.contains("m.360buyimg")) {
                        prefix = "m.360buyimg";
                    } else {
                        prefix = "img";
                    }
                }
                //获取图片路径后缀名
                if (info.contains("gif")) {
                    suffix = "gif";
                } else if (info.contains("jpg")) {
                    suffix = "jpg";
                } else if (info.contains("png")) {
                    suffix = "png";
                } else if (info.contains("jpeg")) {
                    suffix = "jpeg";
                }
                //获取指定字符串之间的内容
                String regx = prefix + "(.*?)" + suffix;
                List<String> result = getInfoByRegx(info, regx);
                path = prefix + result.get(0) + suffix;
                list.add(path);
            }
        }
        return list;
    }

    /**
     * 获取字符串指定内容之间的信息
     * @param str 待截取的字符串
     * @param regx 指定内容
     * @return
     */
    public static List<String> getInfoByRegx(String str, String regx){
        List<String> list = new ArrayList<String>();
        Pattern pattern = Pattern.compile(regx);// 匹配的模式
        Matcher m = pattern.matcher(str);
        while (m.find()) {
            int i = 1;
            list.add(m.group(i));
            i++;
        }
        return list;
    }

}
